import React, { useEffect, useState } from "react";
import {
  Button,
  Form,
  Table,
  Input,
  Popconfirm,
  Modal,
  DatePicker,
  InputNumber,
  Select,
} from "antd";
import "./index.css";
import { getUser, addUser, updateUser, deleteUser } from "../../api/index";
import dayjs from "dayjs";
const User = () => {
  const [params, setParams] = useState({
    name: "",
  });
  const [form] = Form.useForm();
  const [userList, setUserlist] = useState([]);
  const [modalType, setmodalType] = useState(0); // 0为新增 1为编辑
  const [modalVisible, setModalVisible] = useState(false);
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
    },
    {
      title: "年龄",
      dataIndex: "age",
    },
    {
      title: "性别",
      dataIndex: "sex",
    },
    {
      title: "出生日期",
      dataIndex: "birth",
    },
    {
      title: "地址",
      dataIndex: "addr",
    },
    {
      title: "操作",
      render: (rowData) => {
        return (
          <div>
            <Button
              style={{ marginRight: "5px" }}
              type="primary"
              onClick={() => handleClick("edit", rowData)}
            >
              编辑
            </Button>
            <Popconfirm
              title="提示"
              description="您确定要删除这条数据吗?"
              okText="确认"
              cancelText="取消"
              onConfirm={() => handleDelete(rowData)}
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];
  const getUserData = () => {
    getUser(params).then((res) => {
      console.log(res);
      setUserlist(res.list);
    });
  };
  useEffect(() => {
    getUserData();
  }, []);

  const handleClick = (type, rowData) => {
    setModalVisible(true);
    if (type === "add") {
      setmodalType(0);
    } else {
      setmodalType(1);
      const cloneData = JSON.parse(JSON.stringify(rowData));
      cloneData.birth = dayjs(cloneData.birth);
      //数据回显
      form.setFieldsValue(cloneData);
    }
  };
  // 点击ok
  const handleOk = () => {
    console.log(form.getFieldsValue());
    form
      .validateFields()
      .then((values) => {
        values.birth = dayjs(values.birth).format("YYYY-MM-DD");

        if (modalType === 0) {
          addUser(values).then((res) => {
            setModalVisible(false);
            getUserData();
          });
        } else {
          updateUser(values).then((res) => {
            setModalVisible(false);
            getUserData();
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const closeModal = () => {
    setModalVisible(false);
    form.resetFields(); // 清空表单
  };
  const handleDelete = ({ id }) => {
    // const { id } = rowData.id;
    deleteUser({ id }).then((res) => {
      getUserData();
    });
  };
  const handleFinish = (e) => {
    setParams({
      name: e.name,
    });
  };
  useEffect(() => {
    getUserData();
  }, [params]);
  return (
    <div className="userWarpper">
      <div className="top">
        <Button type="primary" onClick={() => handleClick("add")}>
          新增
        </Button>
        <Form layout="inline" onFinish={handleFinish}>
          <Form.Item name="name">
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table
        className="table"
        style={{
          marginTop: 20,
        }}
        columns={columns}
        rowKey={"id"}
        dataSource={userList}
      ></Table>
      <Modal
        title={modalType === 0 ? "新增用户信息" : "编辑用户信息"}
        open={modalVisible}
        onOk={handleOk}
        onCancel={closeModal}
      >
        {
          <>
            <Form
              form={form} // 绑定form实例
              labelCol={{
                span: 4,
              }}
              wrapperCol={{
                span: 18,
              }}
              labelAlign="left"
            >
              {modalType === 1 && (
                <Form.Item name="id" hidden>
                  <Input />
                </Form.Item>
              )}
              <Form.Item
                rules={[{ required: true, message: "请输入用户名" }]}
                label="姓名"
                name="name"
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
              <Form.Item
                rules={[
                  { required: true, message: "请输入年龄" },
                  {
                    type: "number",
                    message: "请输入数字",
                  },
                ]}
                label="年龄"
                name="age"
              >
                <InputNumber
                  style={{ width: "100%" }}
                  placeholder="请输入年龄"
                />
              </Form.Item>
              <Form.Item
                rules={[
                  {
                    required: true,
                    message: "请输入性别",
                  },
                ]}
                label="性别"
                name="sex"
              >
                <Select
                  placeholder="请选择性别"
                  style={{ width: "100%" }}
                  options={[
                    { value: "0", label: "男" },
                    { value: "1", label: "女" },
                  ]}
                />
              </Form.Item>
              <Form.Item
                rules={[
                  {
                    required: true,
                    message: "请输入出生年月",
                  },
                ]}
                label="出生年月"
                name="birth"
              >
                <DatePicker
                  format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style={{ width: "100%" }}
                />
              </Form.Item>
              <Form.Item
                rules={[
                  {
                    required: true,
                    message: "请输入地址",
                  },
                ]}
                label="地址"
                name="addr"
              >
                <Input placeholder="请输入地址" />
              </Form.Item>
            </Form>
          </>
        }
      </Modal>
    </div>
  );
};
export default User;
